import 'package:fate_blind_box/network/http_request.dart';
import 'package:fate_blind_box/ui/cooperation/shop_name/shop_open_time_controller.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../theme/theme_color.dart';
import '../../../utils/common_widget.dart';
import 'package:get/get.dart';
import 'package:date_format/date_format.dart';
import '../../../widget/date_picker/flutter_datetime_picker.dart';

class ShopOpenTimePage extends StatefulWidget {
  bool isFromUpload = false;
  Function? refreshBlock;
  Map<String, dynamic>? resMap;
  Function? callBlock;

  ShopOpenTimePage(
      {Key? key,
      this.refreshBlock,
      this.resMap,
      this.isFromUpload = false,
      this.callBlock})
      : super(key: key);

  @override
  State<ShopOpenTimePage> createState() => _ShopOpenTimePageState();
}

class _ShopOpenTimePageState extends State<ShopOpenTimePage> {
  ShopOpenTimeController editController = Get.put(ShopOpenTimeController());
  TextEditingController startEditVC = TextEditingController();
  TextEditingController endEditVC = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: const Color(0xFFF6F6F6),
      title: '商家营业时间',
      rightActions: [
        UnconstrainedBox(
          child: CupertinoButton(
            padding: EdgeInsets.zero,
            onPressed: () {
              subMitAddressInfo();
            },
            child: Container(
              margin: const EdgeInsets.only(right: 15),
              width: 54,
              height: 31,
              decoration: BoxDecoration(
                color: ThemeColor.appColor,
                borderRadius: BorderRadius.circular(5),
              ),
              alignment: Alignment.center,
              child: const Text(
                '完成',
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
            ),
          ),
        ),
      ],
      childWidget: Container(
        height: 200,
        margin: const EdgeInsets.only(left: 15, right: 15, top: 55),
        padding:
            const EdgeInsets.only(top: 15, bottom: 15, left: 15, right: 15),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            timeItemView(
                name: '开始时间',
                upIdString: editController.startTimeId,
                bindController: startEditVC),
            timeItemView(
                name: '结束时间',
                upIdString: editController.endTimeId,
                bindController: endEditVC),
          ],
        ),
      ),
    );
  }

  Widget timeItemView(
      {TextEditingController? bindController,
      String name = '开始时间',
      String upIdString = ''}) {
    TextStyle textStyle = TextStyle(fontSize: 14, color: ThemeColor.textColor3);
    return Row(
      children: [
        Text(
          name + '：',
          style: textStyle,
        ),
        const SizedBox(
          width: 20,
        ),
        GestureDetector(
          onTap: () {
            choseTimePickerView(
                isStartTime: name.contains('结束') ? false : true);
          },
          child: Container(
            height: 40,
            width: 180,
            decoration: BoxDecoration(
              border: Border.all(color: ThemeColor.appColor, width: 1),
              borderRadius: BorderRadius.circular(25),
            ),
            alignment: Alignment.center,
            child: GetBuilder(
                id: upIdString,
                builder: (ShopOpenTimeController controller) {
                  return TextField(
                    controller: bindController,
                    textAlign: TextAlign.center,
                    enabled: false,
                    style: const TextStyle(fontSize: 18, color: Colors.black),
                    decoration: InputDecoration(
                        isCollapsed: true,
                        border: InputBorder.none,
                        hintText: '请输入$name',
                        hintStyle: const TextStyle(fontSize: 13)),
                  );
                }),
          ),
        ),
      ],
    );
  }

  subMitAddressInfo() async {
    String startTime = startEditVC.text;
    String endTime = endEditVC.text;
    if (startTime.isEmpty) {
      toast('请选择开始时间');
      return;
    }
    if (endTime.isEmpty) {
      toast('请选择结束时间');
      return;
    }

    if(widget.isFromUpload){
      if(widget.callBlock!=null){
        widget.callBlock!(startTime,endTime);
      }
      Get.back();
    }else{
      var res = await HttpRequest.request('match-maker/business/tradeHours',
          params: {'openTime': startTime, 'endTime': endTime});
      if (res['code'] == 0) {
        final data = res['data'];
        if (data != null) {
          toast('保存成功');
          if (widget.refreshBlock != null) {
            widget.refreshBlock!();
          }
          Get.back();
        } else {
          toast(res['msg']);
        }
      }
    }

  }

  @override
  void initState() {
    super.initState();
    if (widget.resMap != null) {
      if (widget.resMap?['openTime'] != null) {
        startEditVC.text = widget.resMap?['openTime'];
      }

      if (widget.resMap?['endTime'] != null) {
        endEditVC.text = widget.resMap?['endTime'];
      }
    }
  }

  void choseTimePickerView({bool isStartTime = true}) {
    //营业时间
    DatePicker.showTimePicker(context, showTitleActions: true,
        onConfirm: (date) {
      if (isStartTime) {
        startEditVC.text = formatDate(date, [HH, ':', nn]);
        editController.update([editController.startTimeId]);
      } else {
        endEditVC.text = formatDate(date, [HH, ':', nn]);
        editController.update([editController.endTimeId]);
      }
    },
        currentTime: DateTime.now(),
        theme: const FlutterDatePickerTheme(
            itemStyle: TextStyle(color: Colors.black, fontSize: 20)),
        locale: LocaleType.zh);
  }
}
